經由昨天我們可以知道,純值在傳遞時是透過複製的方式,而物件則是利用傳參考的方式,今天就來練習幾個關於物件傳參考的範例:
var family = {
name: 'Carol家',
members: {
dad: '老爸',
mom: '老媽',
child: 'Carol'
}
};
var member = family.members;
member.child = 'Mary';
console.log(family);
// {name: 'Carol家', members: {dad: '老爸', mom: '老媽', child: 'Mary'}}
console.log(member);
// {dad: '老爸', mom: '老媽', child: 'Mary'}
member = {
child: 'Jay'
};
console.log(family);
// {name: 'Carol家', members: {dad: '老爸', mom: '老媽', child: 'Mary'}}
console.log(member);
// {dad: '老爸', mom: '老媽', child: 'Jay'}
var a = { x: 1 };
a.y = a;
console.log(a);
var a = { x: 1 };
var b = a;
a.y = a = { x: 2 };
// a = a.y = { x: 2 }; 順序性不影響結果
console.log(a.y); // undefined
console.log(a); // {x: 2}
console.log(b); // {x: 1, y: {x: 2}}
console.log(a === b.y); // true
var a = { x: 1};
var b = a;
a.x = { x: 2};
a.y = a = { y: 1};
console.log(a); // {y: 1}
console.log(b); // {x: {x: 2}, y: {y: 1}}
console.log(a === b.y); // true